package com.lpit.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class ZkSequence {

    RetryPolicy retryPolicy = new ExponentialBackoffRetry(500,3);

    /*原子自增类*/
    private final DistributedAtomicLong distributedAtomicLong;

    public ZkSequence(CuratorFramework cf,String counterPath){
        this.distributedAtomicLong = new DistributedAtomicLong(cf, counterPath, retryPolicy);

    }

    /*生成序列*/
    public Long sequence() throws Exception {
        AtomicValue<Long> atomicValue = this.distributedAtomicLong.increment();
        if(atomicValue.succeeded()){
            return atomicValue.postValue();
        }
        return null;
    }
}
